<?php
error_reporting(7);
$conn = mysqli_connect("localhost", "root", "", "exam");
$mark = 0;//分数
$error = array();
$answer = array('B', 'A', 'B', 'D', 'C', 'C', 'D', 'A', 'B', 'B', 'A', 'D', 'C', 'D', 'A', 'B', 'B', 'B', 'D', 'C', 'A', 'C', 'B', 'D', 'C', 'D', 'A', 'B', 'C', 'D', 'D', 'D', 'C', 'B', 'A', 'B', 'B', 'A', 'D', 'C');
$json = $_POST['json'];
$user_answer = json_decode($json, true);
$i = 0;
if (empty($user_answer)) {
} else {
    foreach ($user_answer as $key => $value) {
        if ($value === $answer[$i])
            $mark += 2.5;
        else
            $error[$key] = $answer[$i];
        $i++;
    }
$sql_insert = "insert into user(mark) values({$mark})";
mysqli_query($conn, $sql_insert);
}
$sql_maxnumber = "select max(id) as maxid from user";
$res = mysqli_query($conn, $sql_maxnumber);
$row = mysqli_fetch_assoc($res);
$max_number = $row['maxid']; //测试人数
$sql_lessmark = "select * from user where mark<={$mark}";
$res2 = mysqli_query($conn, $sql_lessmark);
$lessmark_number = $res2->num_rows;
$percentage = round($lessmark_number * 100 / $max_number, 2);
$error_json = json_encode($error);//错误题

$array = array(
    "mark" => $mark,
    "max_number" => $max_number,
    "percentage" => $percentage . '%',
    "error" => $error_json
);
echo json_encode($array);

?>